package com.techfort.testguice;

import java.util.ArrayList;
import java.util.List;

import roboguice.activity.RoboActivity;
import roboguice.inject.InjectView;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.techfort.tfal.rss.SearchDomParser;
import com.techfort.tfal.utils.ConnectionUtils;
import com.techfort.tfal.utils.NetworkType;

public class Main extends RoboActivity {
	private String librivox = "http://librivox.org/newcatalog/search_xml.php?extended=1";
	private QueryBuilder query;
	
	@InjectView(R.id.genre_spinner) Spinner genreSpinner;
	@InjectView(R.id.lan_spinner) 	Spinner lanSpinner;
	@InjectView(R.id.search_button) Button searchButton;
	@InjectView(R.id.search_string) EditText kw;
	@InjectView(R.id.connectivity) 	TextView conn;
	SQLiteDatabase db;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        
        String [] genres = {
        		"","Dramatic Works","Non-fiction","Fiction","Poetry"
        };
        genreSpinner.setAdapter(new ArrayAdapter<CharSequence>(Main.this, android.R.layout.simple_spinner_item, genres));
        lanSpinner.setAdapter(ArrayAdapter.createFromResource(Main.this, R.array.languages, android.R.layout.simple_spinner_item ));
        searchButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				buildQuery();
				
				ArrayList<Book> books = (ArrayList<Book>) search();
				Log.i("INFO", "Books returned: " + books.size());
				if(books.size()> 0){
					Log.i("INFO", "Book 0: " + books.get(0).getTitle());
					launchResults(books);
				} else {
					notifyNoResults();
				}
			}

		});
        testNetwork();
        
        
    }
    
    private void testNetwork(){
		NetworkType status = ConnectionUtils.checkNetwork(getApplicationContext());
        
        switch(status){
        case WIFI:
        	conn.setText("Connecting through WIFI...");
        	conn.setTextColor(Color.GREEN);
        	searchButton.setEnabled(true);
        	break;
        case MOBILE:
        	conn.setText("WARNING: you are connecting through mobile network, loading might be slow.");
        	conn.setTextColor(Color.YELLOW);
        	searchButton.setEnabled(true);
        	break;
        case NOT_AVAILABLE:
        	searchButton.setEnabled(false);
        	conn.setText("No network available");
        	conn.setTextColor(Color.RED);
        	break;
        }	
	}
	
	private List<Book> search(){
		SearchDomParser parser = new SearchDomParser(query.getQuery());
		List<Book> books = new ArrayList<Book>();
		try {
			books = parser.parse(Book.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return books;
	}
	
	private void buildQuery(){
		query = new QueryBuilder(librivox);
		String genre = genreSpinner.getSelectedItem().toString();
		if(!genre.equals("")){
			query.addGenre(genre);
		}
		
		String language = lanSpinner.getSelectedItem().toString();
		if(!language.equals("")){
			query.addLanguage(language);
		}
		
		String keyword = kw.getText().toString();
		if(!keyword.equals("")){
			query.addKeyword(keyword);
		}
	}
	
	private void notifyNoResults() {
		// TODO Auto-generated method stub
		
	}

	private void launchResults(ArrayList<Book> books) {
		Intent intent = new Intent(Main.this, ResultsActivity.class);
		Bundle bundle = new Bundle();
		bundle.putParcelableArrayList("books", books);
		intent.putExtras(bundle);
		Log.i("INFO", "about to launch activity");
		startActivity(intent);
	}
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.mainmenu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.exit:
			finish();
		case R.id.manage:
			Intent intent = new Intent(Main.this, Manage.class);
			startActivity(intent);
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
	}
	
	@Override
	protected void onDestroy() {
	
		super.onDestroy();
	}
	
}